#include "mainwindow.h"
#include "ui_mainwindow.h"

void MainWindow::initUI()
{
    currentFile = new QLabel("当前文件：");
    ui->statusbar->addWidget(currentFile);
    progress = new QProgressBar;
    progress->setValue(ui->textEdit->font().pointSize());
    ui->statusbar->addWidget(progress);
    fontSizeBox = new QSpinBox;
    fontSizeBox->setValue(ui->textEdit->font().pointSize());
    ui->toolBar->addWidget(new QLabel("字体大小"));
    ui->toolBar->addWidget(fontSizeBox);
    fontNameBox = new QFontComboBox;
    ui->toolBar->addWidget(new QLabel("字体"));
    ui->toolBar->addWidget(fontNameBox);
    QLayout *layout = ui->toolBar->layout();
    layout->setSpacing(10);
    ui->toolBar->setLayout(layout);
    setCentralWidget(ui->textEdit);

    on_textEdit_copyAvailable(false);
}

void MainWindow::initSignalSlots()
{
    connect(fontNameBox, &QFontComboBox::currentFontChanged, this, [&](const QFont &name){
        QTextCharFormat fmt;
        fmt.setFont(name);
        ui->textEdit->mergeCurrentCharFormat(fmt);
    });
    connect(fontSizeBox, &QSpinBox::valueChanged, this, [&](int fontSize) {
        QTextCharFormat fmt;
        fmt.setFontPointSize(fontSize);
        ui->textEdit->mergeCurrentCharFormat(fmt);
        progress->setValue(fontSize);
    });
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initUI();
    initSignalSlots();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_italics_act_triggered(bool checked)
{
    QTextCharFormat fmt;
    fmt.setFontItalic(checked);
    ui->textEdit->mergeCurrentCharFormat(fmt);
}


void MainWindow::on_bold_act_triggered(bool checked)
{
    QTextCharFormat fmt;
    if (checked)
        fmt.setFontWeight(QFont::Bold);
    else
        fmt.setFontWeight(QFont::Normal);
    ui->textEdit->mergeCurrentCharFormat(fmt);
}


void MainWindow::on_underLine_act_triggered(bool checked)
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(checked);
    ui->textEdit->mergeCurrentCharFormat(fmt);
}


void MainWindow::on_textEdit_copyAvailable(bool b)
{
    ui->copy_act->setEnabled(b);
    ui->cut_act->setEnabled(b);
    ui->pase_act->setEnabled(ui->textEdit->canPaste());
}


void MainWindow::on_textEdit_selectionChanged()
{
    QTextCharFormat fmt = ui->textEdit->currentCharFormat();
    ui->italics_act->setChecked(fmt.font().italic());
    ui->bold_act->setChecked(fmt.font().bold());
    ui->underLine_act->setChecked(fmt.font().underline());
}

